package cn.moukou.tongji.ihealth.admin.controller;

import cn.moukou.tongji.ihealth.admin.pojo.Doctor;
import cn.moukou.tongji.ihealth.admin.pojo.DoctorSchedule;
import cn.moukou.tongji.ihealth.admin.service.DoctorScheduleService;
import cn.moukou.tongji.ihealth.admin.service.DoctorService;
import cn.moukou.tongji.ihealth.admin.util.Md5Util;
import cn.moukou.tongji.ihealth.core.bean.Resp;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import org.omg.PortableServer.LIFESPAN_POLICY_ID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;

import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ihealth/admin")
public class ApiController {


    @Autowired(required = false)
    OSS ossClient;

    @Value("${spring.cloud.alicloud.access-key}")
    String accessId;

    @Value("${spring.cloud.alicloud.secret-key}")
    String secretKey;

    @Value("${spring.cloud.alicloud.oss.bucket}")
    String bucket;

    @Value("${spring.cloud.alicloud.oss.endpoint}")
    String endpoint;

    @Autowired
    DoctorService doctorService;

    @Autowired
    DoctorScheduleService scheduleService;

    @GetMapping("/ping")
    public String ping() {
        return "pong";
    }

    @GetMapping("/oss/policy")
    public Map<String , String> ossPolicy() {
        String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint
        String dir = "ihealth/"; // 用户上传文件时指定的前缀。

        try {
            long expireTime = 300;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            java.util.Date expiration = new java.util.Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            Map<String, String> respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            return respMap;

        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return null;
    }

    @GetMapping("/doctor/one/get")
    public Resp<Doctor> getOneDoctor(@RequestParam("id") String id) {
        Doctor doctor = doctorService.getOneDoctor(id);
        return Resp.ok(doctor);
    }

    @PostMapping("/doctor/one/update")
    public Resp<String> updateOneDoctor(@RequestParam("id") String id,
                                        @RequestParam("name") String name,
                                        @RequestParam("phoneNumber") String phoneNumber,
                                        @RequestParam("email") String email,
                                        @RequestParam("doctorInfo") String doctorInfo) {
        Doctor doctor = new Doctor();
        doctor.setId(id);
        doctor.setName(name);
        doctor.setPhoneNumber(phoneNumber);
        doctor.setEmail(email);
        doctor.setDoctorInfo(doctorInfo);
        if(doctorService.updateOneDoctor(doctor)>0) {
            return Resp.ok("修改成功");
        } else {
            return Resp.fail("修改失败");
        }
    }

    @PostMapping("/doctor/avatar/update")
    public Resp<String> updateOneDoctor(@RequestParam("id") String id,
                                        @RequestParam("avatar") String avatar
                                        ) {
        Doctor doctor = new Doctor();
        doctor.setId(id);
        doctor.setAvatar(avatar);
        if(doctorService.updateOneDoctor(doctor)>0) {
            return Resp.ok("修改成功");
        } else {
            return Resp.fail("修改失败");
        }
    }

    @PostMapping("/doctor/pwd/reset")
    public Resp<String> resetDoctorPws(@RequestParam("id") String id) {
        Doctor doctor = new Doctor();
        doctor.setId(id);
        doctor.setPassword(Md5Util.getMD5String("qweqwe"));
        if(doctorService.updateOneDoctor(doctor)>0) {
            return Resp.ok("重置成功");
        } else {
            return Resp.fail("重置失败");
        }
    }

    @GetMapping("/doctor/all/get")
    public Resp<ArrayList<Doctor>> getDoctors() {
        ArrayList<Doctor> doctors = doctorService.getAllDoctors();
        return Resp.ok(doctors);
    }

    @PostMapping("/doctor/add")
    public Resp<String> addDoctor(@RequestParam("uid") String uid,
                                  @RequestParam("name") String name,
                                  @RequestParam("email") String email,
                                  @RequestParam("phoneNumber") String phoneNumber,
                                  @RequestParam("password") String password) {
        Doctor doctor = doctorService.getOneDoctor(uid);
        if (doctor!=null) {
            return Resp.fail("已经存在此工号");
        }
        if(doctorService.addDoctor(uid, name, password, email, phoneNumber)>0){
            return Resp.ok("添加成功");
        } else {
            return Resp.fail("添加失败");
        }
    }

    @GetMapping("/schedule/get")
    public Resp<Object> getScheduleByDate(@RequestParam("date") Date date) {
        ArrayList<DoctorSchedule> doctorSchedules = scheduleService.getSchedulesByDate(date);
        return Resp.ok(doctorSchedules);
    }

    @PostMapping("/schedule/update")
    public Resp<Object> updateSchedule(@RequestParam("date") Date date, @RequestParam("scheduleList") String jsonStr) {
        JSONArray jsonArray = JSON.parseArray(jsonStr);
        List<DoctorSchedule> schedules = jsonArray.toJavaList(DoctorSchedule.class);
        scheduleService.updateSchedules(date, schedules);
        return Resp.ok("更新成功");
    }
}
